#pragma
#include "Socket.hpp"
#include "log.hpp"
#include <iostream>
#include <string>
#include <signal.h>
#include <unistd.h>
#include <functional>

using fun_t = std::function<std::string(std::string &package)>;

class TcpServer {
public:
    TcpServer(uint16_t port, fun_t callback) :port_(port), callback_(callback)
    {}
    bool InitServer()
    {
        listensock_.Socket();
        listensock_.Bind(port_);
        listensock_.Listen();
        LOG(Info, "Init server done...");
        return true;
    }
    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        signal(SIGPIPE, SIG_IGN);
        
        while (true)
        {
            std::string clientip;
            uint16_t clientport;
            int sockfd = listensock_.Accept(&clientip, &clientport);
            if (sockfd < 0) {
                continue;
            }
            // 因为LOG是宏定义过的,所以这个"\"不能少
            // LOG(Info, "accept a new link, sockfd: %d, clientip: %s, \
            // clientport: %d", sockfd, clientip.c_str(), clientport);
            LOG(Info, "accept a new link, sockfd: %d, clientip: %s, clientport: %d", sockfd, clientip.c_str(), clientport);
            // 提供服务, 为了简单暂用多进程替代, 实际情况得用线程池+cp
            if (fork() == 0) {
                listensock_.Close();
                std::string inbuff_stream;

                // 计算数据
                while (true)
                {
                    char buffer[1280];
                    size_t n = read(sockfd, buffer, sizeof(buffer));
                    if (n > 0) {
                        buffer[n] = 0;
                        inbuff_stream += buffer;
                        LOG(Debug, "debug: \n%s", inbuff_stream.c_str());

                        while (true)
                        {
                            std::string info = callback_(inbuff_stream);
                            // inbuff_stream可能存在多个报文
                            // callback_拿完一个报文就清除该报文的数据
                            if (info.empty())  break;  // 检测inbuff_stream中是否还有报文
                            LOG(Debug, "debug: response: \n%s", info.c_str());
                            write(sockfd, info.c_str(), info.size());
                        }
                    }
                    else if (n == 0)  break;
                    else  break;
                }
                exit(0);
            }
            close(sockfd);
        }
    }
    ~TcpServer(){}
private:
    uint16_t port_;
    Sock listensock_;
    fun_t callback_;
};